package middleware

import (
	"time"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/jwt"
)

type userClaims struct {
	Username string `json:"username"`
}

const (
	accessTokenMaxAge  = 30 * time.Minute
	refreshTokenMaxAge = 24 * time.Hour
)

var sigKey = []byte("0581701f-51c4-4e20-9a6d-37ac19024cc7")

func NewGetToken(userName string) (jwt.TokenPair, error) {

	refreshClaims := jwt.Claims{Subject: userName}

	accessClaims := userClaims{
		Username: userName,
	}

	signer := jwt.NewSigner(jwt.HS256, sigKey, accessTokenMaxAge)

	return signer.NewTokenPair(accessClaims, refreshClaims, refreshTokenMaxAge)
}

func NewVerifyMiddleware() iris.Handler {
	verifier := jwt.NewVerifier(jwt.HS256, sigKey)

	verifier.WithDefaultBlocklist()

	return verifier.Verify(func() interface{} {
		return new(userClaims)
	})
}

func NewVerifyToken(refreshToken []byte, userName string) (*jwt.VerifiedToken, error) {

	verifier := jwt.NewVerifier(jwt.HS256, sigKey)

	return verifier.VerifyToken(refreshToken, jwt.Expected{Subject: userName})
}

func NewGetUserClaims(ctx iris.Context) *userClaims {

	claims := jwt.Get(ctx).(*userClaims)

	return claims
}
